package com.atguigu.gmall.common.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.bean.GmallCorrelationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @Description 消息发送确认
 * <p>
 * ConfirmCallback  只确认消息是否正确到达 Exchange 中
 * ReturnCallback   消息没有正确到达队列时触发回调，如果正确到达队列不执行
 * <p>
 * 1. 如果消息没有到exchange,则confirm回调,ack=false
 * 2. 如果消息到达exchange,则confirm回调,ack=true
 * 3. exchange到queue成功,则不回调return
 * 4. exchange到queue失败,则回调return
 *
 */

@Component
@Slf4j
public class MQProducerAckConfig implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    // 修饰一个非静态的void（）方法,在服务器加载Servlet的时候运行，并且只会被服务器执行一次在构造函数之后执行，init（）方法之前执行。
    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);            //指定 ConfirmCallback
        rabbitTemplate.setReturnCallback(this);             //指定 ReturnCallback
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("消息发送成功：" + JSON.toJSONString(correlationData));
        } else {
            log.info("消息发送失败：" + cause + " 数据：" + JSON.toJSONString(correlationData));

            //消息的重试
            this.retryMessage(correlationData);
        }
    }



    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        // 反序列化对象输出
        System.out.println("消息主体: " + new String(message.getBody()));
        System.out.println("应答码: " + replyCode);
        System.out.println("描述：" + replyText);
        System.out.println("消息使用的交换器 exchange : " + exchange);
        System.out.println("消息使用的路由键 routing : " + routingKey);
        //获取消息实体id
        String correlationDataId = (String) message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");
        //获取redis中对应的消息实体
        String correlationDataStr = (String) redisTemplate.opsForValue().get(correlationDataId);
        //转换
        GmallCorrelationData gmallCorrelationData = JSONObject.parseObject(correlationDataStr, GmallCorrelationData.class);

        //重试发送
        this.retryMessage(gmallCorrelationData);

    }

    /**
     * 消息的重试发送
     * @param correlationData
     */
    private void retryMessage(CorrelationData correlationData) {

        //强转
        GmallCorrelationData gmallCorrelationData= (GmallCorrelationData) correlationData;
        //获取重试次数
        int retryCount = gmallCorrelationData.getRetryCount();

        //判断
        if(retryCount>=3){
            //到达次数，拒绝重试
            //  不需要重试了
            log.error("重试次数已到，发送消息失败:"+JSON.toJSONString(gmallCorrelationData));

        }else{//重试发送

            //次数加+1
            retryCount+=1;

            //更新到redis
            gmallCorrelationData.setRetryCount(retryCount);
            System.out.println("重试次数：\t"+retryCount);
            redisTemplate.opsForValue().set(
                    gmallCorrelationData.getId(),
                    JSON.toJSONString(gmallCorrelationData),
                    10,
                    TimeUnit.MINUTES
                    );


            //判断是否为延迟
            if(gmallCorrelationData.isDelay()){
                //发送延迟消息
                rabbitTemplate.convertAndSend(
                        gmallCorrelationData.getExchange(),
                        gmallCorrelationData.getRoutingKey(),
                        gmallCorrelationData.getMessage(),message1 -> {

                    //设置延迟时间
                    message1.getMessageProperties().setDelay(gmallCorrelationData.getDelayTime()*1000);


                    return message1;
                },correlationData);

            }else{

                //发送消息
                rabbitTemplate.convertAndSend(
                        gmallCorrelationData.getExchange(),
                        gmallCorrelationData.getRoutingKey(),
                        gmallCorrelationData.getMessage(),
                        gmallCorrelationData
                );
            }




        }




    }



}
